<template>
  <el-container class="container">
    <el-header class="header">
      <span class="ai-title">职场AI问答</span>
    </el-header>

    <el-main class="main">
      <el-scrollbar ref="scrollbar" class="scrollbar">
        <div
            v-for="(message, index) in messages"
            :key="index"
            class="message-wrapper"
            :class="{ 'user-message-wrapper': message.role === 'user' }"
        >
          <div class="message-bubble" :class="message.role">
            <div class="content">{{ message.content }}</div>
            <div class="time">{{ message.time }}</div>
          </div>
        </div>
        <div v-if="loading" class="loading-wrapper">
          <div class="typing-indicator">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
          </div>
        </div>
      </el-scrollbar>
    </el-main>

    <el-footer class="footer">
      <div class="input-container">
        <el-input
            v-model="question"
            placeholder="请输入你的问题"
            clearable
            @keyup.enter.native="sendQuestion"
            :disabled="loading"
        >
          <template #append>
            <el-button
                type="primary"
                @click="sendQuestion"
                :loading="loading"
                :disabled="!question.trim() || loading"
            >
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </el-footer>
  </el-container>
</template>

<script setup>
import axios from 'axios'
import {ref, nextTick} from 'vue'

const API_URL = BASE_URL + '/chat/send'
const roomId = Math.floor(Math.random() * 10) + 1
const messages = ref([])
const question = ref('')
const loading = ref(false)
const scrollbar = ref(null)

const getCurrentTime = () => {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}

const scrollToBottom = async () => {
  await nextTick()
  if (scrollbar.value) {
    const wrap = scrollbar.value.$el || scrollbar.value // 兼容 Element Plus 的不同版本
    if (wrap) {
      wrap.scrollTop = wrap.scrollHeight
    }
  }
}

const sendQuestion = async () => {
  if (!question.value.trim() || loading.value) return

  const userMessage = {

    content: question.value,
    time: getCurrentTime()
  }

  messages.value.push(userMessage)
  question.value = ''
  loading.value = true

  try {
    const response = await axios.post(API_URL, {
      content: userMessage.content,
      roomId: roomId
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    });
    console.log(response.data);

    const data = response.data
    const aiMessage = {
      content: data,
      time: getCurrentTime()
    }

    messages.value.push(aiMessage)
  } finally {
    loading.value = false
    scrollToBottom()
  }
}
</script>

